import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login'
import store from "../store/index";

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    name:'login',
    component:Login,
    meta:{require:false}
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta:{require:false}
  },
  {
    path:'/index',
    name:'index',
    component: () => import('../views/index.vue'),
    meta:{
      require:true,
      roles:['admin','leader','user']
    },
    children:[
      {
        path:'/index/home',
        name:'home',
        component:()=>import('../views/Home.vue'),
        meta:{
          require:true,
          roles:['boss','leader','user']
        }
      },
      {
        path:'/index/about',
        name:'about',
        component:()=>import('../views/About.vue'),
        meta:{
          require:true,
          roles:['boss','leader']
        }
      },
      {
        path:'/index/userList',
        name:'userList',
        component:()=>import('../views/Userlist.vue'),
        meta:{
          require:true,
          roles:['boss']
        }
      },
      {
        path:'/index',
        component:()=>import('../views/Home.vue'),
        meta:{
          require:true,
          roles:['boss','leader','user']
        }
      },
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to,from,next)=>{
  //判断是否需要验证登录
  if(to.meta.require){
    console.log(store.state.user)
    //判断是否登录
    if (store.state.user.userName){
      // console.log(store.state.user.type)
      // console.log(to.meta.roles)
      if (to.meta.roles.indexOf(store.state.user.type)>=0){
        next()
      }else {
        router.push('/login')
      }

    }else {
      alert('还没有登录，请登录后再进！')
      router.push('/login')
    }
  }else {
    next()
  }
})

export default router
